<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      size="mini"
      style="margin:10px 20px"
      @click="dialogFormVisible=true"
    >新增角色</el-button>
    <el-table
      :data="data"
      style="margin:10px 20px"
      :default-sort="{prop: 'date', order: 'descending'}"
      border
      size="mini"
      header-row-class-name="header"
    >
      <el-table-column type="index" label="序号" sortable width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="角色名" sortable></el-table-column>
      <el-table-column prop="description" label="描述" sortable></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row}">
          <a @click="dialogBeforeOpen(row.id)">分配权限</a>
          <a @click="update(row)">修改</a>
          <a class="del" @click="delRole(row.id)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-size="size"
      layout="->, total, prev, pager, next"
      :total="total"
    ></el-pagination>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="formName">
        <el-form-item label="角色名称" label-width="100px" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="100px">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateRole()">确 定</el-button>
        <el-button @click="close()">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改权限"
      :visible.sync="dialogVisible"
      width="width"
      :before-close="dialogBeforeClose"
    >
      <div>
        <el-tree
          :props="props"
          :data="roleList"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="isChecks"
          ref="tree"
        ></el-tree>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="updatePermission">确 定</el-button>
        <el-button @click="dialogBeforeClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (this.data.some(item => item.name == value)) {
        if (this.form.id && this.name == value) {
          callback();
        } else {
          callback(new Error("角色名已存在"));
        }
      }
      callback();
    };
    return {
      data: [],
      page: 1,
      size: 5,
      total: 0,
      form: {},
      name: "",
      dialogFormVisible: false,
      dialogVisible: false,
      rules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
          { validator: validateName, trigger: "blur" }
        ]
      },
      props: {
        label: "name",
        children: "children"
      },
      roleList: [],
      isChecks: [],
      roleId: ""
    };
  },
  mounted() {
    this.getRoles();
  },
  computed: {
    title() {
      return this.form.id ? "更新角色" : "添加角色";
    }
  },
  methods: {
    handleCurrentChange(val) {
      this.page = val;
      this.getRoles();
    },

    //获取角色列表
    async getRoles() {
      let result = await this.$api.setting.getRoles(this.page, this.size);
      if (result.total > 0) {
        if (result.rows.length > 0) {
          this.total = result.total;
          this.data = result.rows;
        } else {
          this.page--;
          this.getRoles();
        }
      }
    },
    //删除角色
    delRole(id) {
      this.$confirm("确认删除吗?", {
        cancelButtonText: "取消",
        confirmButtonText: "确认"
      })
        .then(async res => {
          await this.$api.setting.delRoleById(id);
          this.$message.success("删除成功!");
          this.getRoles();
        })
        .catch(err => {});
    },

    //添加角色
    addOrUpdateRole() {
      this.$refs["formName"].validate(async valid => {
        if (valid) {
          try {
            if (this.form.id) {
              let result = await this.$api.setting.updateRole(this.form);
              this.$message.success("更新成功");
            } else {
              await this.$api.setting.addRole(this.form);
              this.$message.success("添加成功");
            }
            this.dialogFormVisible = false;
            this.getRoles();
          } catch (error) {}
        } else {
          return false;
        }
      });
    },

    //打开更新对话框
    update(row) {
      this.form = cloneDeep(row);
      this.dialogFormVisible = true;
      this.name = row.name;
    },

    //关闭对话款
    close() {
      this.dialogFormVisible = false;
      this.form = {};
      this.name = "";
    },

    //关闭权限对话款
    dialogBeforeClose() {
      this.dialogVisible = false;
      this.roleList = [];
      this.isChecks = [];
      this.roleId = "";
    },

    //打开权限对话款
    dialogBeforeOpen(id) {
      this.getPermissionsList();
      this.getRolesById(id);
      this.dialogVisible = true;
      this.roleId = id;
    },
    async getPermissionsList() {
      let list = await this.$api.role.getPermissionList();
      this.roleList = this.treeOfList(list, "0");
    },
    treeOfList(list, flag) {
      let arr = [];
      list.forEach(element => {
        if (element.pid == flag) {
          let children = this.treeOfList(list, element.id);
          if (children.length) {
            element.children = children;
          }
          arr.push(element);
        }
      });
      return arr;
    },
    async getRolesById(userId) {
      try {
        let { permIds } = await this.$api.setting.gelRolesById(userId);
        this.isChecks = permIds;
      } catch (error) {}
    },
    async updatePermission() {
      let roleIds = this.$refs.tree.getCheckedKeys();
      await this.$api.setting.updatePermission({
        id: this.roleId,
        permIds: roleIds
      });
      this.$message.success("修改成功!");
      this.dialogBeforeClose();
    }
  }
};
</script>

<style>
a {
  font-size: 12px;
  color: blue;
  margin-right: 20px;
}
.del {
  color: darkgrey !important;
}
.header {
  background-color: red;
}
</style>